package utils

import (
	"errors"
	"fmt"
	"io/ioutil"
	"net/http"
	"net/url"
	"os"
	"time"

	"github.com/spf13/viper"
	"go.uber.org/zap"
)

func SendWorkWechatMsg(msg string) error {
	if Log() != nil {
		Log().Debug(msg)
	}

	if IsLocalDev() {
		return nil
	}

	names := viper.GetString("notify.users")
	env := ""
	if IsProduction() {
		env = "生产环境"
	}
	if IsQa() {
		env = "测试环境"
	}

	if IsLocalDev() {
		env = "本地环境"
	}

	serverIp, _ := os.Hostname()
	content := "Project: %s\nEnv: %s\nTime: %s"
	content = fmt.Sprintf(content, viper.GetString("name"), env, time.Now().Format(DateFormatTimestamp))
	content += "\nServerHost: " + serverIp
	content += "\nMsg: " + msg
	return AlertWorkWechat(names, content)
}

// AlertWorkWechat 发送消息
// names string 使用多个名字英文逗号隔开，
// msg 消息
func AlertWorkWechat(names string, msg string) error {
	if len(names) == 0 || len(msg) == 0 {
		return errors.New("请指定接收人或消息内容")
	}

	domain := "https://growth-sso-api.shruisong.net"
	uri := domain + "/api/alarm/send"
	data := url.Values{}
	data.Set("users", names)
	data.Set("content", msg)
	http.DefaultClient.Timeout = time.Second
	resp, err := http.PostForm(uri, data)
	if err != nil {
		return err
	}
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return err
	}
	logger := Log()
	if logger != nil {
		logger.Debug("alert weixin msg ret", zap.ByteString("response", body))
	}

	return nil
}
